var express = require('express');
var router = express.Router();
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

var timestamp = (new Date()).valueOf(); 

var dataSuccess = {
    status: 'success', 
    message:'提交成功',
    data: {
        successid: 'success'+timestamp
    }
};
var dataError = {
    status: 'error'
};
var fileNo = {
    status: 'error',
    message:'未找到'
};
//登录接口
router.post('/login',function (req, res, next) {
    // 打印post请求的数据内容
    var datas = req.body
    console.log(req.body.userid);
    // var JsonObj=JSON.parse(fs.readFileSync('./output.json'));
    // console.log(JsonObj);
    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
    res.header('Access-Control-Allow-Origin', '*');
    fs.writeFileSync('./db/'+ datas.userid +'.json',JSON.stringify(req.body));
    if (req.body) {
        res.end(JSON.stringify(dataSuccess));
    } else {
        res.end(JSON.stringify(dataError));
    }

});

//查询接口
router.get('/getdetiles', function(req, res, next) {
    var datas = req.query
    res.header('Access-Control-Allow-Origin', '*');
    // var JsonObj=JSON.parse(fs.readFileSync('./db/'+ datas.userid +'.json'));
    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
    var filename = datas.userid+'.json';
    fs.readdir('./db/', function(err, files) {
    var hasFile = false;
        for(var i=0;i<files.length;i++){
            // console.log(!(files[i]==filename))
            if(!(files[i]==filename)){
                hasFile = false
            }else{
                hasFile = true
                break
            }
        }
        if(hasFile){
            var JsonObj=JSON.parse(fs.readFileSync('./db/'+filename ));
            res.end(JSON.stringify(JsonObj));
        }else{
            res.end(JSON.stringify(fileNo));
        }
        return hasFile;
    })

    
});

var xsssuccess = {
    status: 'success',
    message:'你的信息已经被我提交到服务器,哇卡卡卡-- from laosiji'
};
// xss test
router.get('/myxss', function(req, res, next) {
    var datas = req.query
    res.header('Access-Control-Allow-Origin', '*');
    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
    console.log(datas)
    res.end(JSON.stringify(xsssuccess));
});


var csrfsuccess = {
    status: 'success',
    message:'你的内容已经被我删除了,哇卡卡卡-- from laosiji'
};
// csrf test
router.get('/mycsrf', function(req, res, next) {
    var datas = req.query
    res.header('Access-Control-Allow-Origin', '*');
    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
    console.log(datas)
    res.end(JSON.stringify(csrfsuccess));
});

module.exports = router;
